/*
 *   This file is part of <open-parametrics>
 *   Copyright (c) 2006-2008 Miguel-Angel Sicilia
 *
 *   open-parametrics is free software: you can redistribute it and/or modify
 *   it under the terms of the Lesser GNU General Public License as
 *   published by the Free Software Foundation, either version 3 of
 *   the License, or (at your option) any later version.
 *
 *   open-parametrics is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with open-parametrics.  If not, see <http://www.gnu.org/licenses/>.
 */

package es.uah.cc.ie.parametrics.regress;

import es.uah.cc.ie.parametrics.CERGenerator;
import es.uah.cc.ie.parametrics.CostDriver;
import es.uah.cc.ie.parametrics.CostEstimatingRelationship;
import es.uah.cc.ie.parametrics.Dataset;
import es.uah.cc.ie.parametrics.Variable;
import flanagan.analysis.Regression;



/**
 * Defines the basic interface for a technique to generate CERs from
 * Datasets using linear regression.
 *
 *
 * @author Miguel-Angel Sicilia
 */
public  class SimpleNonLinearRegressionCERGenerator extends CERGenerator{

    /**
     * The underlying regression model.
     */
    private Regression _model;
    /**
     * Constructs the CERGenerator.
     */
    public SimpleNonLinearRegressionCERGenerator(String label){
        super(label);
    }

    /**
     * Creates a CER through linear regression on the instances in the
     * dataset.
     *
     * @param ds The dataset used for the generation
     * @return The CER
     */
    @Override
    public CostEstimatingRelationship generate(CostDriver[] x, Variable y,
            Dataset ds) {
       // this model supports only a cost driver:
        assert(x.length == 1);
        ExponentialFunction f = new ExponentialFunction();

        // get the data un arrays:
        double[][] data = ds.getXYSlice(x[0], y);

     
        double[] xarr = new double[data.length];
        double[] yarr = new double[data.length];
        for (int i = 0; i < data.length; i++){
                xarr[i] = data[i][0];
                yarr[i] = data[i][1];
            }

        double[] start = new double[2];
        start[0]=0.1;  start[1]=0.1;
         _model = new Regression(xarr, yarr);
        _model.simplex(f, start);
        System.out.println(_model.getBestEstimates()[0] +","+
                _model.getBestEstimates()[1]);
        System.out.println(_model.getAdjustedR());

        return new SimpleSingleNonLinearRegressionCER("generated",
                f, _model.getBestEstimates());

    }


}